import { prototype as ArrayPrototype } from './ArrayPrototype.js'
// import { watchers } from './Watcher.js'
import Dep from './Dep.js'

export default class Observe {
  //需要监测的数据
  constructor(data) {
    this.walk(data)
  }
  walk(data) {
    if (typeof data != 'object' || data == null) return
    //判断是否为数组
    if (Array.isArray(data)) {
      //重置原型对象
      Object.setPrototypeOf(data, ArrayPrototype)
    }
    Object.keys(data).forEach((key) => {
      this.defineReactive(data, key, data[key])
    })
  }

  defineReactive(data, key, value) {
    this.walk(value)
    const dep = new Dep()
    Object.defineProperty(data, key, {
      get() {
        window.$watcher && dep.push(window.$watcher)
        return value
      },
      set: (newValue) => {
        if (newValue == value) return
        this.walk(newValue)
        value = newValue
        dep.notify()
      },
    })
  }
}
